package com.sky.controller.admin;


import com.sky.config.DomainNameConfig;
import com.sky.entity.FileData;
import com.sky.mapper.FileDataMapper;
import com.sky.result.Result;
import lombok.Data;
import org.apache.ibatis.mapping.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/admin/common")
public class CommonController {

    /**
     * 文件上传
     * @param file
     * @return
     */
    @Autowired
    private FileDataMapper fileDataMapper;

    @Autowired
    private DomainNameConfig domainNameConfig;

    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
       log.info("文件上传：{}", file);
        try {
            // 创建文件实体
            FileData fileData = new FileData();
            //生成文件UUid
            String fileUuid = UUID.randomUUID().toString();
            //获得文件后缀
            String fileExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            // 构建文件路径
            String filePath = fileUuid + fileExtension;

            fileData.setFileName(filePath);
            fileData.setFileData(file.getBytes());

            // 保存到数据库
            fileDataMapper.insert(fileData);

           //获取配置文件的下载url
           String downloadPath = domainNameConfig.getUrl() + "/admin/common/download?filePath=" + filePath;

            return Result.success(downloadPath);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.error("MessageConstant.FILE_UPLOAD_FAILED");
        }
    }

    /**
     * 文件下载
     * @param filePath
     * @return
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> download(String filePath) {
    log.info("文件下载：{}", filePath);
    try {
        // 从数据库查询文件数据
        FileData fileData = fileDataMapper.selectByFileName(filePath);
        if (fileData == null) {
            return ResponseEntity.notFound().build();
        }

        // 获取文件原始名称（如果存储了的话）
        String originalFileName = fileData.getFileName();

        // 设置响应头，指示浏览器下载文件
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", originalFileName);

        // 返回文件数据
        return new ResponseEntity<>(fileData.getFileData(), headers, HttpStatus.OK);
    } catch (Exception e) {
        log.error("文件下载失败", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
}

}
